package com.wssnail.elasticsearch.config;

import com.wssnail.elasticsearch.properties.ElasticsearchProperties;
import com.wssnail.elasticsearch.util.ElasticSearchUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: 熟透的蜗牛
 * @CreateTime: 2023-01-05 16:44
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticsearchAutoConfig {

    @Autowired
    private ElasticsearchProperties elasticsearchProperties;

    private static final String HTTP = "http";

    @Bean("elasticSearchUtils")
    @ConditionalOnMissingBean
    ElasticSearchUtils elasticSearchUtils() {
        return new ElasticSearchUtils(restHighLevelClient());
    }

    @Bean
    RestHighLevelClient restHighLevelClient() {
        String hosts = elasticsearchProperties.getHosts();
        if (StringUtils.isBlank(hosts)) {
            throw new RuntimeException("spring.elasticsearch.rest.uris is blank");
        }
        String[] uriArr = hosts.split(",");
        HttpHost[] httpHostArr = new HttpHost[uriArr.length];
        int i = 0;
        for (String uri : uriArr) {
            if (StringUtils.isEmpty(hosts)) {
                continue;
            }
            try {
                //拆分出ip和端口号
                String[] split = uri.split(":");
                String host = split[0];
                String port = split[1];
                HttpHost httpHost = new HttpHost(host, Integer.parseInt(port), HTTP);
                httpHostArr[i++] = httpHost;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        RestClientBuilder builder = RestClient.builder(httpHostArr);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (StringUtils.isNotBlank(elasticsearchProperties.getUserName()) && StringUtils.isNotBlank(elasticsearchProperties.getPassword())) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(elasticsearchProperties.getUserName(), elasticsearchProperties.getPassword()));
            builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        }
        // 连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeOut());
            requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeOut());
            requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeOut());
            return requestConfigBuilder;
        });
        // 连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectNum());
            httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectNumPerRoute());
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }
}
